# -*- coding:utf-8 -*-
import time

import requests
import json
from Common.ReadYaml import ConfigYaml
from Common.Log import MyLog
log = MyLog()
import urllib3
urllib3.disable_warnings()
try:
    JSONDecodeError = json.decoder.JSONDecodeError
except AttributeError:
    JSONDecodeError = ValueError



class FeiShu(object):

    def __init__(self):
        '''
        '''
        self.fei_shu_json = ConfigYaml("fei_shu_json").base_config
        self.fei_shu_type = ConfigYaml("fei_shu_type").base_config
        self.requests_url = ConfigYaml("fei_shu_url").base_url
        self.headers = {self.fei_shu_type: self.fei_shu_json}

    def judge_msg(self, msg):
        """
        判断消息是否为空
        """
        if msg and msg.strip():
            return True
        else:
            return False

    def send_text(self, data):
        """
        消息类型为text类型
        :param msg: 消息内容
        :return: 返回消息发送结果
        """

        return self.post(data)

    def post(self, data):
        """
        发送消息（内容UTF-8编码）
        :param data: 消息数据（字典）
        :return: 返回消息发送结果
        """
        try:
            post_data = json.dumps(data)
            response = requests.post(self.requests_url, headers=self.headers, data=post_data, verify=False)
        except requests.exceptions.HTTPError as exc:
            log.error("消息发送失败， HTTP error: %d, reason: %s" % (exc.response.status_code, exc.response.reason))
            raise
        except requests.exceptions.ConnectionError:
            log.error("消息发送失败，HTTP connection error!")
            raise
        except requests.exceptions.Timeout:
            log.error("消息发送失败，Timeout error!")
            raise
        except requests.exceptions.RequestException:
            log.error("消息发送失败, Request Exception!")
            raise
        else:
            try:
                result = response.json()
            except JSONDecodeError:
                log.error("服务器响应异常，状态码：%s，响应内容：%s" % (response.status_code, response.text))
                return {'errcode': 500, 'errmsg': '服务器响应异常'}
            else:
                log.debug('发送结果：%s' % result)
                if result.get('errcode', True):
                    time_now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
                    error_data = {
                        "msgtype": "text",
                        "text": {
                            "content": "[注意-自动通知]飞书机器人消息发送失败，时间：%s，原因：%s，请及时跟进，谢谢!" % (
                                time_now, result['errmsg'] if result.get('errmsg', False) else '未知异常')
                        },
                        "at": {
                            "isAtAll": False
                        }
                    }
                    log.error("消息发送失败，自动通知：%s" % error_data)
                    requests.post(self.requests_url, headers=self.headers, data=json.dumps(error_data))
                return result



